<?php
/*
 * 获取手机验证码
 */
namespace app\home\logic;

use think\Model;

use think\Session;
use Yunpian\Sdk\YunpianClient;

class Phone extends Model {

    private $phone = '';//手机号

    private $phoneFormat = '/^1\d{10}$/'; //手机号码正则表达式

    public function setPhone($phone) {
        $this->phone = $phone;
    }

    //短信功能是否开启
    public function isMobileEnabled() {
        if (config('con_sms_status') == 0) {
            return false;
        }
        return true;
    }

    //手机号是否为空
    public function isPhoneEmpty() {
        if (empty($this->phone)) {
            return false;
        }
        return true;
    }

    //手机号格式是否正确
    public function isPhone() {
        if (preg_match($this->phoneFormat, $this->phone)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否已经发送过验证码
     * param $code 对应的session码
     * param $limitTime 限制时间(单位：秒)
     */
    public function isSended($codeType, $timeType, $phoneType, $phone, $limitTime) {
        if (session($codeType)) {
            if (session($phoneType) == $phone && (session($timeType) + $limitTime > time())) {
                return false;
            }
        }
        return true;
    }

    //获取发送验证码URL
    public function getSendUrl() {
        return config('con_sms_url');
    }

    //生成随机验证码
    private function createCode($len) {
        srand((double) microtime() * 1000000);
        $char = '0,1,2,3,4,5,6,7,8,9';
        $list = explode(",", $char);
        $code = '';
        for ($i = 0; $i < $len; $i++) {
            $randnum = rand(0, 9);
            $code .= $list[$randnum];
        }
        return $code;
    }

    //获取手机验证码
    public function getCode($data = []) {
        $this->setPhone($data['phone']);//手机号赋值
        $res = array('code' => 0);
        if (!$this->isMobileEnabled()) {
            $res['msg'] = '手机短信功能已关闭';
            return $res;
        }
        if (!$this->isPhoneEmpty()) {
            $res['msg'] = '手机号码不能为空';
            return $res;
        }
        if (!$this->isPhone()) {
            $res['msg'] = '请输入正确的手机号码';
            return $res;
        }
        if (!$data['type']) {
            $res['msg'] = '类型不能为空';
            return $res;
        }
        $sms_code = 'sms_' . $data['type'];
        $sms_time = $sms_code . '_time';
        $sms_phone = $sms_code . '_phone';
        $limit_time = $data['limit'];
        if (!$this->isSended($sms_code, $sms_time, $sms_phone, $data['phone'], $limit_time)) {
            $res['msg'] = '请1分钟后再试';
            return $res;
        }

        $smsUrl = 'https://sms.yunpian.com/v1/sms/send.json';
        if (empty($smsUrl)) {
            $res['msg'] = '请求失败,请联系客服';
            return $res;
        }
        $code = $this->createCode(6);
        $mobile = $this->phone;
        $apikey = '82d9e2592739b0574dd313af91bea114';
        $text = '【小雨投资】您本次操作的验证码是：'.$code.', 请在20分钟内使用。验证码仅限本人使用，如非本人操作请忽略。';
        $result = send_sms($apikey, $text, $mobile);

        if ($result) {
            session($sms_code, $code);
            session($sms_time, time());
            session($sms_phone, $data['phone']);
            $sdata['user_id'] = isset($data['user_id']) ? $data['user_id'] : 0;
            $sdata['type'] = $data['type'];
            $sdata['phone'] = $this->phone;
            $sdata['contents'] = $text;
            $sdata['send_return'] = $result;
            $sdata['send_url'] = $smsUrl;
            $sdata['code'] = $code;
            $id = model('approve_smslog')->add($sdata);
            return ['code' => 1, 'msg' => $id];
        } else {
            $res['msg'] = '请求失败,请稍后重试';
            return $res;
        }
    }

    public function checkCode($data = []) {
        $rs = model('approve_smslog')->getOne($data);
        return $rs ?: false;
    }

    //更新手机验证码
    public function setCodeStatus($where = []) {
        $rs = db('approve_smslog')->where($where)->update([
                'code_status' => 1,
                'code_time' => time()
        ]);
        return $rs ?: false;
    }
}